package com.wdd.libbase.base

import android.os.Bundle
import androidx.annotation.MainThread
import androidx.appcompat.app.AppCompatActivity
import com.fengchen.uistatus.UiStatusController
import com.fengchen.uistatus.annotation.UiStatus
import com.wdd.libbase.annotation.BindEventBus
import com.wdd.libbase.mvp.IView
import com.wdd.libbase.view.HttpDialog
import leakcanary.AppWatcher
import org.greenrobot.eventbus.EventBus

/**
 *
 * @ProjectName:    OwnTool
 * @Package:        com.wdd.libbase.base
 * @ClassName:      BaseActivity
 * @Description:     java类作用描述
 * @Author:         王丹丹
 * @CreateDate:     2019/12/9 10:27
 * @UpdateUser:     更新者
 * @UpdateDate:     2019/12/9 10:27
 * @UpdateRemark:   更新说明
 * @Version:        1.0
 */
abstract class BaseActivity : AppCompatActivity(), IView {
    //请求加载框
    private var httpDialog: HttpDialog? = null
    protected var mUiStatusController: UiStatusController? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getLayoutId())
        inject()
        initView()
        initData()
        //判断是否需要注册EventBus
        if (this::class.java.isAnnotationPresent(BindEventBus::class.java) &&
            !EventBus.getDefault().isRegistered(this)
        ) {
            EventBus.getDefault().register(this)
        }
    }


    /**
     * 获取布局文件
     * @return
     */
    @MainThread
    protected abstract fun getLayoutId(): Int

    /**
     * 初始化布局
     */
    @MainThread
    open fun initView() {
        mUiStatusController = UiStatusController.get().bind(this)
        mUiStatusController!!.changeUiStatus(UiStatus.CONTENT)
        mUiStatusController!!.setListener(
            UiStatus.EMPTY
        ) { _, _, _ ->
            retryLoad()
        }

        mUiStatusController!!.setListener(
            UiStatus.LOAD_ERROR
        ) { _, _, _ ->
            retryLoad()
        }
    }

    /**
     * 初始化数据
     */
    @MainThread
    protected abstract fun initData()

    /**
     * dagger2注入操作
     */
    @MainThread
    open fun inject() {

    }


    /**
     * 点击重试
     */
    @MainThread
    open fun retryLoad() {

    }

    /**
     * 展示加载弹窗
     */
    override fun showHttpLoading() {
        if (httpDialog == null) {
            httpDialog = HttpDialog(this)
        }
        if (!httpDialog!!.isShowing) {
            httpDialog!!.show()
        }
    }

    /**
     *隐藏弹窗
     */
    override fun hideHttpLoading() {
        if (httpDialog != null && httpDialog!!.isShowing) {
            httpDialog!!.dismiss()
        }
    }


    override fun onDestroy() {
        hideHttpLoading()
        httpDialog = null
        if (this::class.java.isAnnotationPresent(BindEventBus::class.java) &&
            EventBus.getDefault().isRegistered(this)
        ) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
        AppWatcher.objectWatcher.watch(this)
    }
}